<?php

namespace app\api\validate;

use think\exception\ValidateException;
use think\Validate;
use app\common\model\user\Vip;
use app\common\model\user\VipExpire;
class VipValidate extends Validate
{
    protected $rule = [
        'vip_id' => 'require|integer|gt:0',
    ];

    protected $message = [
        'vip_id.require' => '缺少参数！',
        'vip_id.integer' => 'VIP ID必须是整数',
        'vip_id.gt' => 'VIP ID必须大于0',
    ];

    // 验证场景
    protected $scene = [
        'upVip' => ['vip_id'],
    ];

    // 自定义验证方法：检查VIP是否存在
    public function checkVipExists($vipId)
    {
        $vipLevel = Vip::where('status', 1)->where('id', $vipId)->find();
        if (empty($vipLevel)) {
            throw new ValidateException('VIP不存在');
        }
        return $vipLevel;
    }



    // 自定义验证方法：检查用户余额是否足够
    public function checkUserBalance($userinfo, $vipLevel)
    {
        if ($userinfo['money'] < $vipLevel['sale_price']) {
            throw new ValidateException('余额不足');
        }
        return true;
    }

    // 自定义验证方法：检查用户是否已经是永久会员
    public function checkUserVipStatus($userinfo)
    {
        $userVipRecord = $userinfo->userVipExpire();
        if ($userVipRecord && $userVipRecord['is_long'] == 1) {
            throw new ValidateException('您已经是永久会员了');
        }
        return true;
    }

    public function checkVipIsRepeat($userinfo, $vipLevel){
        if($vipLevel['is_repeat'] == 0){
            $c = VipExpire::where('user_id',$userinfo['id'])->where('vip_id', $vipLevel['id'])->count();
            if ($c > 0) {
                throw new ValidateException('该VIP只能购买一次');
            }
        }
    }
}